package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
	"unsafe"

	"github.com/wenzhenxi/gorsa"
)

var Pubkey = `-----BEGIN RSA Public Key-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApr8LgfbNiH1jHEHa9iPU
FX5+1DCVGNLquRuYd6DtyV8n/NqajHYuKKPsB34AULQTEb+qALRmEQp2RgysBiz0
KYlk8ISCJKC6Bp/r56MmnrDIoSaag3BMQnCu9QMKMDDwJe5A5CVVwcFLu5C3uCmV
WNKUlIkH6hsrTBYcK+67yBLVgSgtm6ewE2n+q4BrwhOziCs4KXhIW10t3WpNT5dr
rYSHgjIhg3wVJVJZmdAtHj1xl0ZGRe5IxCIVOEaMRAouRA2keJXJFcICzD5S7URE
PnDD0c0XqLq52SrMw0f+7GD4iM/1hlLesBuQDqJiLCLvP7BDqdTT0GChKAK+yWP8
wQIDAQAB
-----END RSA Public Key-----
`

type EnParams struct {
	Username    string `json:"username"` //加入标签给字段的json格式命名
	Time        int    `json:"time"`
	ExternalUid string `json:"external_uid"`
}

func Post(url string, data interface{}, contentType string) string {

	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	jsonStr, _ := json.Marshal(data)
	resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

// 公钥加密私钥解密
func main() {

	now := time.Now()

	en_params := EnParams{
		Username:    "admin",
		Time:        int(now.Unix()),
		ExternalUid: "",
	}
	data, err := json.Marshal(&en_params)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	pubenctypt, _ := gorsa.PublicEncrypt(string(data), Pubkey)
	fmt.Println("加密字符串：", pubenctypt)

	url := "http://" + os.Args[1] + "/api/v1/user/token/generate"

	body_data := make(map[string]string)
	body_data["username"] = "admin"
	body_data["encrypt"] = pubenctypt

	bytesData, _ := json.Marshal(body_data)

	res, err := http.Post(url, "application/json;charset=utf-8", bytes.NewBuffer([]byte(bytesData)))
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
	}
	defer res.Body.Close()

	content, err := ioutil.ReadAll(res.Body)
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
	}

	str := (*string)(unsafe.Pointer(&content)) //转化为string,优化内存
	fmt.Println(*str)

}
